package org.cweili.rayminder.gui

import groovy.swing.SwingBuilder
import groovy.util.logging.Commons
import org.cweili.rayminder.service.NoteService
import org.cweili.rayminder.util.Beans
import org.cweili.rayminder.util.Global
import org.cweili.rayminder.util.Utils

import java.awt.*
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent

/**
 *
 * @author Cweili
 * @version 2013年8月22日 下午10:12:17
 *
 */
@Commons
@Singleton(lazy = true)
class Tray {

	Tray() {
		if (!SystemTray.supported) {
			log.error('This system not support tray.')
			Utils.quit()
		}

		def menu = new SwingBuilder().popupMenu() {
			menuItem(text: Global.APP_NAME, iconTextGap: -10, enabled: false)
			separator()
			menuItem(text: '主界面', icon: GuiUtils.icon('date'), actionPerformed: {
				Utils.openUrl(Global.APP_INDEX)
			})
			menuItem(text: '配置', icon: GuiUtils.icon('settings'), actionPerformed: {
				GuiUtils.showAlarmDialog(Beans.get(NoteService).nextAlarmNote)
			})
			separator()
			menuItem(text: '关于', icon: GuiUtils.icon('id-card'), actionPerformed: {
				GuiUtils.showAboutDialog()
			})
			menuItem(text: '退出', icon: GuiUtils.icon('block'), actionPerformed: {
				GuiUtils.showQuitDialog()
			})
		}

		Global.TRAY = new TrayIcon(GuiUtils.icon('date').image, Global.APP_NAME).with {
			imageAutoSize = true
			addMouseListener([
					mouseReleased: { MouseEvent e ->
						if (e.button == MouseEvent.BUTTON1) {
							Utils.openUrl(Global.APP_INDEX)
						} else if (e.popupTrigger) {
							menu.location = [e.x, e.y]
							menu.invoker = menu
							menu.visible = true
						}
					}
			] as MouseAdapter)
			it
		}

		try {
			SystemTray.systemTray.add(Global.TRAY)
		} catch (Exception e) {
			log.error('Add system tray error.', e)
			Utils.quit()
		}
	}

}
